package com.example.springdocdemo.rest;

import com.example.springdocdemo.vo.Book;
import com.example.springdocdemo.vo.BookRepository;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.Random;

@RestController
@RequestMapping("/api/book")
public class BookController {

	private final BookRepository repository;

	/**
	 * Instantiates a new Book controller.
	 *
	 * @param repository the repository
	 */
	public BookController(BookRepository repository) {
		this.repository = repository;
	}

	/**
	 * 根据id获取书籍信息
	 *
	 * @param id the id
	 * @return the book
	 */
	@GetMapping("/findById/{id}")
	public Book findById(@PathVariable long id)  {
        try {
            return repository.findById(id)
                    .orElseThrow(() -> new Exception("没有找到"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

	/**
	 * 获取书籍列表
	 *
	 * @return the collection
	 */
	@GetMapping("/findBooks")
	public Collection<Book> findBooks() {
		return repository.getBooks();
	}

	/**
	 * 更新书籍信息
	 *
	 * @param id   the id
	 * @param book the book
	 * @return the book
	 */
	@PutMapping("/updateBook/{id}")
	@ResponseStatus(HttpStatus.OK)
	public Book updateBook(@PathVariable("id") final Integer id, @RequestBody final Book book) {
		book.setId(id);
		repository.add(book);
		return book;
	}

	/**
	 * post方式提交书籍信息
	 *
	 * @param book the book
	 * @return the book
	 */
	@PostMapping("/postBook")
	@ResponseStatus(HttpStatus.CREATED)
	public Book postBook(@NotNull @Valid @RequestBody final Book book) {
		book.setId(new Random().nextInt(20));
		repository.add(book);
		return book;
	}

	/**
	 * Head book book.
	 *
	 * @return the book
	 */
	@RequestMapping(method = RequestMethod.HEAD, value = "/")
	@ResponseStatus(HttpStatus.OK)
	public Book headBook() {
		return new Book();
	}

	/**
	 * 根据id删除书籍
	 *
	 * @param id the id
	 * @return the long
	 */
	@DeleteMapping("/deleteBook/{id}")
	@ResponseStatus(HttpStatus.OK)
	public long deleteBook(@PathVariable final long id) {
		repository.removeBookById(id);
		return id;
	}
}
